<template>
  <div class="serial-debug">
    <el-card class="page-header" shadow="never">
      <h2>串口调试工具</h2>
      <p>支持串口通信调试和数据监控</p>
    </el-card>

    <div class="debug-container">
      <!-- 串口配置区域 -->
      <el-card class="config-panel" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>串口配置</span>
            <el-button 
              :type="isConnected ? 'danger' : 'primary'" 
              @click="toggleConnection"
              :loading="connecting"
            >
              {{ isConnected ? '关闭串口' : '打开串口' }}
            </el-button>
          </div>
        </template>

        <el-form :model="serialConfig" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="串口端口">
                <el-select v-model="serialConfig.port" :disabled="isConnected" placeholder="选择串口">
                  <el-option 
                    v-for="port in availablePorts" 
                    :key="port.device" 
                    :label="`${port.device} - ${port.description}`" 
                    :value="port.device" 
                  />
                </el-select>
                <el-button @click="refreshPorts" :disabled="isConnected" style="margin-left: 10px;">
                  刷新
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="波特率">
                <el-select v-model="serialConfig.baud_rate" :disabled="isConnected">
                  <el-option label="1200" :value="1200" />
                  <el-option label="2400" :value="2400" />
                  <el-option label="4800" :value="4800" />
                  <el-option label="9600" :value="9600" />
                  <el-option label="19200" :value="19200" />
                  <el-option label="38400" :value="38400" />
                  <el-option label="57600" :value="57600" />
                  <el-option label="115200" :value="115200" />
                  <el-option label="230400" :value="230400" />
                  <el-option label="460800" :value="460800" />
                  <el-option label="921600" :value="921600" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数据位">
                <el-select v-model="serialConfig.data_bits" :disabled="isConnected">
                  <el-option label="8" :value="8" />
                  <el-option label="7" :value="7" />
                  <el-option label="6" :value="6" />
                  <el-option label="5" :value="5" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="停止位">
                <el-select v-model="serialConfig.stop_bits" :disabled="isConnected">
                  <el-option label="1" :value="1" />
                  <el-option label="1.5" :value="1.5" />
                  <el-option label="2" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="校验位">
                <el-select v-model="serialConfig.parity" :disabled="isConnected">
                  <el-option label="无" value="none" />
                  <el-option label="奇校验" value="odd" />
                  <el-option label="偶校验" value="even" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="流控制">
                <el-select v-model="serialConfig.flow_control" :disabled="isConnected">
                  <el-option label="无" value="none" />
                  <el-option label="硬件" value="hardware" />
                  <el-option label="软件" value="software" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="连接状态">
            <el-tag :type="isConnected ? 'success' : 'info'">
              {{ isConnected ? '已连接' : '未连接' }}
            </el-tag>
            <span v-if="isConnected" style="margin-left: 10px; color: #909399;">
              {{ serialConfig.port }} - {{ serialConfig.baud_rate }}bps
            </span>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 数据收发区域 -->
      <el-row :gutter="20" class="data-panels">
        <!-- 发送区域 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>数据发送</span>
                <el-button type="primary" @click="handleSendData" :disabled="!isConnected">
                  发送
                </el-button>
              </div>
            </template>

            <el-form>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="发送格式">
                    <el-radio-group v-model="sendFormat" style="display: flex;">
                      <el-radio label="text">文本</el-radio>
                      <el-radio label="hex">十六进制</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束符">
                    <el-checkbox-group v-model="endChars" style="display: flex;">
                      <el-checkbox label="\r">回车符(\r)</el-checkbox>
                      <el-checkbox label="\n">换行符(\n)</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item>
                <el-input
                  v-model="sendText"
                  type="textarea"
                  :rows="15"
                  placeholder="请输入要发送的数据..."
                  :disabled="!isConnected"
                />
              </el-form-item>

              <el-form-item>
                <el-checkbox v-model="autoSend">定时发送</el-checkbox>
                <el-input-number 
                  v-model="sendInterval" 
                  :min="100" 
                  :max="60000" 
                  :disabled="!autoSend"
                  style="margin-left: 10px; width: 120px;"
                />
                <span style="margin-left: 5px;">ms</span>
              </el-form-item>

              <!-- 快捷发送按钮 -->
              <el-form-item label="快捷发送">
                <div class="quick-send">
                  <el-button size="small" @click="quickSend('AT')" :disabled="!isConnected">AT</el-button>
                  <el-button size="small" @click="quickSend('AT+GMR')" :disabled="!isConnected">AT+GMR</el-button>
                  <el-button size="small" @click="quickSend('AT+RST')" :disabled="!isConnected">AT+RST</el-button>
                  <el-button size="small" @click="quickSend('\\r\\n')" :disabled="!isConnected">回车换行</el-button>
                </div>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 接收区域 -->
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>数据接收</span>
                <div>
                  <el-button @click="clearReceiveData">清空</el-button>
                  <el-button @click="saveReceiveData">保存</el-button>
                </div>
              </div>
            </template>

            <el-form>
              <el-form-item label="显示格式">
                <el-radio-group v-model="receiveFormat">
                  <el-radio label="text">文本</el-radio>
                  <el-radio label="hex">十六进制</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item>
                <el-input
                  v-model="receiveData"
                  type="textarea"
                  :rows="15"
                  placeholder="接收到的数据将显示在这里..."
                  readonly
                />
              </el-form-item>

              <el-form-item>
                <el-checkbox v-model="autoScroll">自动滚动</el-checkbox>
                <el-checkbox v-model="showTimestamp" style="margin-left: 20px;">显示时间戳</el-checkbox>
              </el-form-item>
              
              <!-- 占位元素，保持与发送区域高度一致 -->
              <el-form-item label="">
                <div style="height: 32px;"></div>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>

      <!-- 统计信息 -->
      <el-card shadow="hover" class="stats-panel">
        <template #header>
          <span>通信统计</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-statistic title="发送字节数" :value="stats.send_bytes || 0" />
          </el-col>
          <el-col :span="4">
            <el-statistic title="接收字节数" :value="stats.receive_bytes || 0" />
          </el-col>
          <el-col :span="4">
            <el-statistic title="发送次数" :value="stats.send_count || 0" />
          </el-col>
          <el-col :span="4">
            <el-statistic title="接收次数" :value="stats.receive_count || 0" />
          </el-col>
          <el-col :span="4">
            <el-statistic title="错误次数" :value="stats.error_count || 0" />
          </el-col>
          <el-col :span="4">
            <el-statistic title="连接时长" :value="connectionTime" suffix="s" />
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { serialApi } from '../api'

// 串口配置
const serialConfig = reactive({
  port: '',
  baud_rate: 115200,
  data_bits: 8,
  stop_bits: 1,
  parity: 'none',
  flow_control: 'none'
})

// 可用串口列表
const availablePorts = ref([])

// 连接状态
const isConnected = ref(false)
const connecting = ref(false)
const connectionStartTime = ref(0)
const connectionTime = computed(() => {
  if (!isConnected.value) return 0
  return Math.floor((Date.now() - connectionStartTime.value) / 1000)
})

// 数据发送
const sendText = ref('')
const sendFormat = ref('text')
const endChars = ref(['\\n'])
const autoSend = ref(false)
const sendInterval = ref(1000)

// 数据接收
const receiveData = ref('')
const receiveFormat = ref('text')
const autoScroll = ref(true)
const showTimestamp = ref(true)

// 保存原始接收数据，用于格式切换
const rawReceiveData = ref([])

// 监听receiveFormat变化，实现实时格式转换
watch(receiveFormat, () => {
  refreshReceiveDataDisplay()
})

// 根据当前格式刷新接收数据显示
const refreshReceiveDataDisplay = () => {
  if (rawReceiveData.value.length === 0) {
    receiveData.value = ''
    return
  }
  
  // 清空当前显示数据
  receiveData.value = ''
  
  // 重新格式化并显示所有原始数据
  rawReceiveData.value.forEach(item => {
    const timestamp = item.timestamp ? `[${new Date(item.timestamp * 1000).toLocaleTimeString()}] ` : ''
    const displayData = receiveFormat.value === 'hex' ? item.hex_data : item.data
    receiveData.value += timestamp + displayData + '\n'
  })
}

// 统计信息
const stats = reactive({
  send_bytes: 0,
  receive_bytes: 0,
  send_count: 0,
  receive_count: 0,
  error_count: 0
})

let sendTimer = null
let websocket = null

// 刷新串口列表
const refreshPorts = async () => {
  try {
    const response = await serialApi.getPorts()
    if (response.success) {
      // 后端返回的数据结构是 {success: true, message: '', data: {ports: [...]}}
      availablePorts.value = response.data.ports || []
      ElMessage.success('串口列表已刷新')
    } else {
      ElMessage.error(response.message || '获取串口列表失败')
    }
  } catch (error) {
    console.error('刷新串口列表失败:', error)
    ElMessage.error('刷新串口列表失败: ' + error.message)
  }
}

// 建立/断开连接
const toggleConnection = async () => {
  if (isConnected.value) {
    await disconnect()
  } else {
    await connect()
  }
}

// 连接串口
const connect = async () => {
  if (!serialConfig.port) {
    ElMessage.warning('请选择串口端口')
    return
  }

  try {
    connecting.value = true
    
    const response = await serialApi.connect(serialConfig)
    
    if (response.success) {
      isConnected.value = true
      connectionStartTime.value = Date.now()
      
      // 建立WebSocket连接用于接收数据
      websocket = serialApi.createWebSocket(
        serialConfig.port,
        onWebSocketMessage,
        onWebSocketClose,
        onWebSocketError
      )
      
      ElMessage.success(response.message)
      
      // 重置统计
      Object.assign(stats, { send_bytes: 0, receive_bytes: 0, send_count: 0, receive_count: 0, error_count: 0 })
      
      // 开始获取状态
      startStatusPolling()
      
    } else {
      ElMessage.error(response.message)
    }
    
  } catch (error) {
    ElMessage.error('打开串口失败: ' + error.message)
  } finally {
    connecting.value = false
  }
}

// 断开连接
const disconnect = async () => {
  try {
    connecting.value = true
    
    // 停止定时发送
    if (sendTimer) {
      clearInterval(sendTimer)
      sendTimer = null
    }
    
    // 关闭WebSocket
    if (websocket) {
      websocket.close()
      websocket = null
    }
    
    // 关闭后端串口连接
    if (serialConfig.port) {
      const response = await serialApi.disconnect(serialConfig.port)
      if (response.success) {
        ElMessage.info(response.message)
      }
    }
    
    isConnected.value = false
    
  } catch (error) {
    ElMessage.error('关闭串口失败: ' + error.message)
  } finally {
    connecting.value = false
  }
}

// 发送数据
const handleSendData = async () => {
  if (!isConnected.value) {
    ElMessage.warning('请先打开串口')
    return
  }
  
  // 检查发送数据是否为空或undefined
  const baseData = sendText.value || ''
  if (!baseData.trim()) {
    ElMessage.warning('请输入要发送的数据')
    return
  }
  
  try {
    let dataToSend = baseData
    
    // 添加结束符
    if (endChars.value.includes('\\r')) {
      dataToSend += '\r'
    }
    if (endChars.value.includes('\\n')) {
      dataToSend += '\n'
    }
    
    console.log('串口发送数据:', {
      port: serialConfig.port,
      data: dataToSend,
      format: sendFormat.value
    })
    
    const response = await serialApi.sendData(
      serialConfig.port,
      dataToSend,
      sendFormat.value
    )
    
    if (response.success) {
      ElMessage.success(response.message)
      
      // 更新统计信息
      stats.send_count++
      stats.send_bytes += dataToSend.length
      
      // 如果启用了定时发送
      if (autoSend.value && !sendTimer) {
        sendTimer = setInterval(handleSendData, sendInterval.value)
      }
    } else {
      ElMessage.error(response.message)
    }
    
  } catch (error) {
    console.error('串口发送数据错误:', error)
    ElMessage.error('发送失败: ' + error.message)
  }
}

// 快捷发送
const quickSend = async (data) => {
  sendText.value = data
  await handleSendData()
}

// WebSocket消息处理
const onWebSocketMessage = (data) => {
  if (data.type === 'data') {
    // 保存原始数据到数组中，用于后续格式切换
    rawReceiveData.value.push({
      data: data.data,
      hex_data: data.hex_data,
      timestamp: showTimestamp.value ? data.timestamp : null
    })
    
    // 更新当前显示
    const timestamp = showTimestamp.value ? `[${new Date(data.timestamp * 1000).toLocaleTimeString()}] ` : ''
    const displayData = receiveFormat.value === 'hex' ? data.hex_data : data.data
    receiveData.value += timestamp + displayData + '\n'
    
    // 自动滚动
    if (autoScroll.value) {
      // 实现自动滚动逻辑
      setTimeout(() => {
        const textarea = document.querySelector('textarea[readonly]');
        if (textarea) {
          textarea.scrollTop = textarea.scrollHeight;
        }
      }, 0);
    }
  }
}

const onWebSocketClose = () => {
  console.log('WebSocket连接已关闭')
}

const onWebSocketError = (error) => {
  console.error('WebSocket错误:', error)
  ElMessage.error('实时数据连接出现错误')
}

// 状态轮询
const startStatusPolling = () => {
  const poll = async () => {
    if (!isConnected.value || !serialConfig.port) return
    
    try {
      const status = await serialApi.getStatus(serialConfig.port)
      if (status.connected && status.stats) {
        Object.assign(stats, status.stats)
      }
    } catch (error) {
      console.error('获取状态失败:', error)
    }
    
    if (isConnected.value) {
      setTimeout(poll, 2000)
    }
  }
  
  setTimeout(poll, 2000)
}

// 清空接收数据
const clearReceiveData = () => {
  receiveData.value = ''
  rawReceiveData.value = []
}

// 保存接收数据
const saveReceiveData = () => {
  if (!receiveData.value) {
    ElMessage.warning('没有数据可保存')
    return
  }
  
  try {
    const blob = new Blob([receiveData.value], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `serial_receive_${Date.now()}.txt`
    a.click()
    URL.revokeObjectURL(url)
    
    ElMessage.success('数据已保存')
  } catch (error) {
    ElMessage.error('保存失败: ' + error.message)
  }
}

// 组件挂载时初始化
onMounted(() => {
  refreshPorts()
})

// 清理定时器
onUnmounted(() => {
  if (sendTimer) {
    clearInterval(sendTimer)
  }
  if (websocket) {
    websocket.close()
  }
})
</script>

<style scoped>
.serial-debug {
  padding: 20px;
  height: 100vh;
  overflow-y: auto;
}

.page-header {
  margin-bottom: 20px;
  border: none;
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
}

.debug-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.config-panel {
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-panels {
  margin: 0;
}

.quick-send {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.stats-panel {
  border: none;
}

.el-card {
  border-radius: 8px;
}

.el-statistic {
  text-align: center;
}
</style>